package org.truenewx.tnxjee.repo.jdbc.flyway;

import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import org.flywaydb.core.internal.jdbc.JdbcTemplate;
import org.truenewx.tnxjee.core.Strings;
import org.truenewx.tnxjee.repo.jdbc.util.JdbcUtil;

/**
 * Flyway迁移工具类
 */
public class FlywayMigrationUtil {

    private FlywayMigrationUtil() {
    }

    public static boolean existsTable(JdbcTemplate jdbcTemplate, String tableName) throws SQLException {
        return JdbcUtil.existsTableOrView(getMetaData(jdbcTemplate), getSchema(jdbcTemplate), tableName, true);
    }

    public static String getSchema(JdbcTemplate jdbcTemplate) throws SQLException {
        return JdbcUtil.getSchema(getMetaData(jdbcTemplate));
    }

    public static DatabaseMetaData getMetaData(JdbcTemplate jdbcTemplate) throws SQLException {
        return jdbcTemplate.getConnection().getMetaData();
    }

    /**
     * 判断指定表中是否存在指定索引
     *
     * @param jdbcTemplate JdbcTemplate
     * @param tableName    表名
     * @param indexName    索引名
     * @return 指定表中是否存在指定索引
     */
    public static boolean existsIndex(JdbcTemplate jdbcTemplate, String tableName, String indexName) throws Exception {
        String schema = getSchema(jdbcTemplate);
        return jdbcTemplate.queryForInt(
                "select count(*) from information_schema.statistics where table_schema=? and table_name=? and index_name=?",
                schema, tableName, indexName) > 0;
    }

    public static String getInCondition(int size) {
        StringBuilder condition = new StringBuilder();
        if (size > 0) {
            condition.append(Strings.LEFT_BRACKET);
            for (int i = 0; i < size; i++) {
                condition.append(Strings.QUESTION).append(Strings.COMMA);
            }
            condition.deleteCharAt(condition.length() - 1);
            condition.append(Strings.RIGHT_BRACKET);
        }
        return condition.toString();
    }

}
